use std::time::Duration;

use benimator::{Animation, FrameRate};
use bevy::{core::Name, prelude::*, sprite::Sprite, time::Time, winit::WinitWindows};
use soukoban::direction::Direction;

use crate::{components::{AnimationState, Board, MainCamera, Player}, resources::PlayerMovement};


pub fn set_windows_icon(winit_windows: NonSend<WinitWindows>){
    let (icon_rgba,icon_width,icon_height) = {
        let icon_path = crate::settings::static_resources_dir().join("assets/textures/box.png"); 
        let image = image::open(&icon_path)
            .expect("failed to open icon path")
            .into_rgba8();

        let (width,height) = image.dimensions();
        let rgba = image.into_raw();

        (rgba,width,height)
    };

    let icon = winit::window::Icon::from_rgba(icon_rgba, icon_width, icon_height).unwrap();
    for window in winit_windows.windows.values() {
        window.set_window_icon(Some(icon.clone()));
    }
}


pub fn setup_camera(mut commands: Commands) {
    commands.spawn((
        Name::new("Camera"),
        Camera2d,
        MainCamera::default()
    ));
}


pub fn animate_player(
    mut player: Query<(&mut AnimationState, &mut Sprite),With<Player>>,
    mut board: Query<&mut Board>,
    timer: Res<Time>,
    player_movement: Res<PlayerMovement>,
){
    let board = &mut board.single_mut().board;
    let (animations_tate,sprite) = &mut player.single_mut();

    let player_orientation = board.player_orientation();

    let face_up = Animation::from_indices([9], FrameRate::from_frame_duration(Duration::MAX));
    let face_down = Animation::from_indices([6], FrameRate::from_frame_duration(Duration::MAX));
    let face_left = Animation::from_indices([15], FrameRate::from_frame_duration(Duration::MAX));
    let face_right = Animation::from_indices([12], FrameRate::from_frame_duration(Duration::MAX)); 

    let move_up = Animation::from_indices(9..=9 + 2,FrameRate::from_fps(6.0));
    let move_down = Animation::from_indices(6..=6 + 2,FrameRate::from_fps(6.0));
    let move_left = Animation::from_indices(15..= 15 + 2,FrameRate::from_fps(6.0));
    let move_right = Animation::from_indices(12..=12 + 2,FrameRate::from_fps(6.0));

    let animation = if player_movement.directions.is_empty() {
        match player_orientation {
            Direction::Up => face_up,
            Direction::Right => face_right,
            Direction::Down => face_down,
            Direction::Left => face_left,
        }
    }else {
        match player_orientation {
            Direction::Up => move_up,
            Direction::Right => move_right,
            Direction::Down => move_down,
            Direction::Left => move_left,
        }
    };

    animations_tate.update(&animation, timer.delta());
    sprite.texture_atlas.as_mut().unwrap().index = animations_tate.frame_index();

}